﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
using frmPrincipalTestes;

namespace frmPrincipal
{
    public partial class frmCadSales : Form
    {
        private StandardDBConnection standardDBConnection = new StandardDBConnection();
        private float total;
        private List<float> selectedProductsPrices = new List<float>();
        private List<int> selectedProductsAmounts = new List<int>();
        private List<int> selectedProductsCodes = new List<int>();

        public frmCadSales()
        {
            this.total = 0;
            InitializeComponent();
        }
        private void frmCadSales_Load(object sender, EventArgs e)
        {
            DateTime agora = DateTime.Now;
            lblDataSale.Text = agora.ToString("dd/MM/yyyy");
        }

        //Relacionado ao Formulário
        private void CleanForm()
        {
            txtAttendantCode.Enabled = true;
            txtAttendantCode.Text = "";
            lblAttendant.Text = "";
            txtCostumerCPF.Enabled = true;
            txtCostumerCPF.Text = "";
            lblCostumer.Text = "";
            txtProduct.Text = "";
            lstFoundProducts.Items.Clear();
            lstSelectedForSale.Items.Clear();
            selectedProductsAmounts.Clear();
            selectedProductsPrices.Clear();
            TotalRefresh();
        }
        private void TotalRefresh()
        {
            this.total = 0;
            for(int count = 0; count < selectedProductsAmounts.Count; count++){
                this.total += selectedProductsAmounts[count] * selectedProductsPrices[count];
            }
            
            lblTotal.Text = string.Format("Valor Total: R$ {0:#,##0.00}", this.total);
        }


        //Preenche Attendant
        private void FillAttendant()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;

            string sqlCommandText;

            if (!Testes.ValidCode(txtAttendantCode.Text))
            {
                MessageBox.Show("Forneça um código válido!", "Pesquisa Attendant", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            sqlCommandText = "SELECT * FROM atendente WHERE cod_atend = " + txtAttendantCode.Text;
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            databaseDataReader = sqlCommand.ExecuteReader();

            if (databaseDataReader.HasRows)
            {
                databaseDataReader.Read();
                lblAttendant.Text = databaseDataReader["nome_atend"].ToString();
            }

            txtAttendantCode.Enabled = false;
            databaseDataReader.Close();
            databaseDataReader.Dispose();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void txtCodigo_Leave(object sender, EventArgs e)
        {
            FillAttendant();
        }

        //Preenche Cliente
        private void FillCostumer()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;

            string sqlCommandText;
           
            if (!Testes.ValidCPF(txtCostumerCPF.Text))
            {
                MessageBox.Show("Forneça um CPF válido!", "Código Cliente", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            sqlCommandText = "SELECT * FROM cliente WHERE cpf = '" + txtCostumerCPF.Text + "' ";
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            databaseDataReader = sqlCommand.ExecuteReader();

            if (!databaseDataReader.HasRows)
            {
                MessageBox.Show("Código não encontrado", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                databaseDataReader.Read();
                lblCostumer.Text = databaseDataReader["nome_cliente"].ToString();
                txtCostumerCPF.Enabled = false;
            }

            databaseDataReader.Close();
            databaseDataReader.Dispose();
            sqlCommand.Dispose();

            this.Cursor = Cursors.Default;
        }
        private void txtCostumer_Leave(object sender, EventArgs e)
        {
             FillCostumer();
        }

        //Pesquisar Produtos
        private void SearchProduct()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;
            string sqlCommandText, aux;
            int auxcodigo;
            float auxpreco;

            this.Cursor = Cursors.WaitCursor;

            sqlCommandText = "SELECT * FROM produto " +
                    "WHERE nome_prod ILIKE '%" + txtProduct.Text + "%' " +
                    "ORDER BY nome_prod ";

            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = sqlCommandText;
            sqlCommand.Connection = standardDBConnection.cnn;
            databaseDataReader = sqlCommand.ExecuteReader();

            lstFoundProducts.Items.Clear();
            if (!databaseDataReader.HasRows)
                lstFoundProducts.Items.Add("Nenhum produto com este nome encontrado!");
            else
                while (databaseDataReader.HasRows)
                {
                    databaseDataReader.Read();
                    aux = databaseDataReader["nome_prod"].ToString();
                    auxcodigo = Convert.ToInt32(databaseDataReader["cod_prod"].ToString());
                    auxpreco = Convert.ToSingle(databaseDataReader["preco_venda"].ToString());
                    lstFoundProducts.Items.Add(string.Format("{0:00000} - {1}  R$ {2:###.00}", auxcodigo, aux, auxpreco));
                }
            databaseDataReader.Close();
            databaseDataReader.Dispose();
            sqlCommand.Dispose();

            this.Cursor = Cursors.Default;
        }
        private void btnSearchProduct_Click(object sender, EventArgs e)
        {
            SearchProduct();
        }
        private void txtProduct_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
                SearchProduct();
        }

        //Selecionar Produtos
        private void SelectProduct()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;
            string aux, sqlCommandText;
            int auxcodigo, qtd = 0;
            float auxpreco, precoTotal;
            frmQtdSale qtdForm;

            if (lstFoundProducts.SelectedIndex == -1)
            {
                MessageBox.Show("Por favor, selecione um produto.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
                try
                {
                    auxcodigo = Convert.ToInt32(lstFoundProducts.Items[lstFoundProducts.SelectedIndex].ToString().Substring(0, 5));
                    sqlCommandText = "SELECT * FROM produto WHERE cod_prod = " + auxcodigo.ToString();

                    sqlCommand.CommandType = CommandType.Text;
                    sqlCommand.CommandText = sqlCommandText;
                    sqlCommand.Connection = standardDBConnection.cnn;
                    databaseDataReader = sqlCommand.ExecuteReader();

                    databaseDataReader.Read();
                    qtdForm = new frmQtdSale(databaseDataReader["nome_prod"].ToString());
                    qtdForm.FormClosing += (closingSender, closedE) => { qtd = qtdForm.GetQtd(); };
                    qtdForm.ShowDialog();

                    aux = databaseDataReader["nome_prod"].ToString();
                    auxcodigo = Convert.ToInt32(databaseDataReader["cod_prod"].ToString());
                    auxpreco = Convert.ToSingle(databaseDataReader["preco_venda"].ToString());
                    precoTotal = auxpreco * qtd;

                    this.selectedProductsAmounts.Add(qtd);
                    this.selectedProductsPrices.Add(auxpreco);
                    this.selectedProductsCodes.Add(auxcodigo);
                    lstSelectedForSale.Items.Add(string.Format("{0:00000} - {1}  R$ {2:###.00} x {3:000} = R$ {4:####.00}", auxcodigo, aux, auxpreco, qtd, precoTotal));

                    TotalRefresh();

                    databaseDataReader.Close();
                    databaseDataReader.Dispose();
                    sqlCommand.Dispose();

                }
                catch
                {
                    MessageBox.Show("Selecione um Produto!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
        private void btnSelectProduct_Click(object sender, EventArgs e)
        {
            SelectProduct();
        }
        private void lstProduct_DoubleClick(object sender, EventArgs e)
        {
            SelectProduct();
        }

        //Botões
        //Limpa todos os campos        
        private void btnNew_Click(object sender, EventArgs e)
        {
            CleanForm();
        }
        //Limpa Pesquisa de produtos
        private void btnClean_Click(object sender, EventArgs e)
        {
            lstFoundProducts.Items.Clear();
        } 
        //Remove Produto Selecionado
        private void btnRemoveProduto_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;
            string sqlCommandText;
            int auxcodigo;

            if (lstFoundProducts.SelectedIndex == -1)
            {
                MessageBox.Show("Por favor, selecione um produto que deseja remover.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
                auxcodigo = Convert.ToInt32(lstSelectedForSale.Items[lstSelectedForSale.SelectedIndex].ToString().Substring(0, 5));
                sqlCommandText = "SELECT * FROM produto WHERE cod_prod = " + auxcodigo.ToString();

                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.CommandText = sqlCommandText;
                sqlCommand.Connection = standardDBConnection.cnn;
                databaseDataReader = sqlCommand.ExecuteReader();

                selectedProductsAmounts.RemoveAt(lstSelectedForSale.SelectedIndex);
                selectedProductsPrices.RemoveAt(lstSelectedForSale.SelectedIndex);
                lstSelectedForSale.Items.RemoveAt(lstSelectedForSale.SelectedIndex);
                TotalRefresh();

                databaseDataReader.Close();
                databaseDataReader.Dispose();
                sqlCommand.Dispose();
            }
        }
        //Salva a venda no Banco de Dados
        private void btnSaveSale_Click(object sender, EventArgs e)
        {
            //será feito 2 inserts -> venda, contem e trigger -> AtualizaProduto
            //será necessário: data, cod_atend, cpf cliente, qtd e cod_prod
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;
            string sqlSale, sqlContem, auxSql, aux;
            DialogResult resp = new DialogResult();
            DateTime agora = DateTime.Now;

            resp = MessageBox.Show("Confirmar Sale de " + lblTotal.Text + " para " + lblCostumer.Text + " ?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (resp == DialogResult.Yes)
            {

                this.Cursor = Cursors.WaitCursor;

                sqlSale = "INSERT INTO venda (cod_atendente, dt_venda, cpf_cliente) " +
                            "VALUES(" + txtAttendantCode.Text + ",'" + agora.ToString("dd/MM/yyyy") +
                            "','" + txtCostumerCPF.Text + "'); ";

                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.CommandText = sqlSale;
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommand.ExecuteNonQuery();
                sqlCommand.Dispose();

                auxSql = "SELECT last_value FROM venda_cod_venda_seq";
                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.CommandText = auxSql;
                sqlCommand.Connection = standardDBConnection.cnn;
                databaseDataReader = sqlCommand.ExecuteReader();

                databaseDataReader.Read();
                aux = databaseDataReader["last_value"].ToString();
                databaseDataReader.Close();
                databaseDataReader.Dispose();
                for (int count = 0; count < lstSelectedForSale.Items.Count; count++)
                {
                    sqlContem = "INSERT INTO contem (cod_venda, quantidade, cod_produto) VALUES(" +
                             aux + ", " + selectedProductsAmounts[count] + ", " + selectedProductsCodes[count] + ");";

                    sqlCommand.CommandType = CommandType.Text;
                    sqlCommand.CommandText = sqlContem;
                    sqlCommand.Connection = standardDBConnection.cnn;
                    sqlCommand.ExecuteNonQuery();
                    sqlCommand.Dispose();
                }
                this.Cursor = Cursors.Default;
                //MessageBox com valor total
                MessageBox.Show("Sale de " + lblTotal.Text + ": Confirmada!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //CleanForm
                CleanForm();

            }
        }
        //Cancela Sale e Fecha o Formulário
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
